import axios from 'axios';
import {
  Message, MessageBox
} from 'element-ui';
import store from '../store';
import {
  getToken
} from 'utils/auth';

// 创建axios实例
const service = axios.create({
	baseURL: '', // api的base_url
    timeout: 30000 // 请求超时时间
});

// request拦截器
service.interceptors.request.use(config => {
  // Do something before request is sent
    if(sessionStorage.getItem('access-token')){
        config.headers['access-token'] = sessionStorage.getItem('access-token') // 让每个请求携带token--['X-Token']为自定义key 请根据实际情况自行修改
    //	config.headers['Admin-token'] = getToken();
    }

    if( !localStorage.getItem('companyId') && config.url != '/auth/token' ){
        let timeMsg;
        if(localStorage.getItem('locale') === 'zh_cn'){
            timeMsg = '闲置时间过长，请重新登录';
        }else if(localStorage.getItem('locale') === 'zh_tw'){
            timeMsg = '閒置時間過長，請重新登入';
        }else{
            timeMsg = 'Idle for too long, please re-login';
        }
        Message({ message: timeMsg, duration: 3 * 1000 });
        setTimeout(function(){
            sessionStorage.removeItem('access-token');
            localStorage.clear(); 
            location.reload();
        }, 4000);
    }
  return config;
}, error => {
  // Do something with request error
  console.log(error); // for debug
  Promise.reject(error);
})

// respone拦截器
service.interceptors.response.use(
  response => {
    /**
     * 下面的注释为通过response自定义code来标示请求状态，当code返回如下情况为权限有问题，登出并返回到登录页
     * 如通过xmlhttprequest 状态码标识 逻辑可写在下面error中
     */

    // console.log(response);
    if( !localStorage.getItem('companyId') && response.config.url != '/auth/token' ){
        let timeMsg;
        if(localStorage.getItem('locale') === 'zh_cn'){
            timeMsg = '闲置时间过长，请重新登录';
        }else if(localStorage.getItem('locale') === 'zh_tw'){
            timeMsg = '閒置時間過長，請重新登入';
        }else{
            timeMsg = 'Idle for too long, please re-login';
        }
        Message({ message: timeMsg, duration: 3 * 1000 });
        setTimeout(function(){
            sessionStorage.removeItem('access-token');
            localStorage.clear(); 
            location.reload();
        }, 4000);
    }

     const res = response.data;
    if (response.status == 401 || res.status == 401 || res.status == 403) {
   	  // location.href = 'localhost/login';
    	// alert('token失效，返回到登录页');
    	sessionStorage.removeItem('access-token');
      this.$router.push({ name: '登录', }).then(() => {
		sessionStorage.removeItem('access-token');
		// localStorage.clear(); 
        location.reload(); // 为了重新实例化vue-router对象 避免bug
      });
      return Promise.reject('error');
    }
    if (response.status !== 200 && res.status !== 200) {
      Message({
        message: res.message,
        type: 'error',
        duration: 5 * 1000
      });
    } else {
      return response.data;
	}
		
  },
  error => {
    console.log('err' + error); // for debug
		let errMsg;
		let timeMsg;
    if(localStorage.getItem('locale') === 'zh_cn'){
    	 errMsg = '请稍候再试';
    	 timeMsg = '闲置时间过长，请重新登录';
    }else if(localStorage.getItem('locale') === 'zh_tw'){
    	 errMsg = '請稍後再試';
    	 timeMsg = '閒置時間過長，請重新登入';
    }else{
    	 errMsg = 'Please try again later';
    	 timeMsg = 'Idle for too long, please re-login';
    }
    if(error.message === 'Request failed with status code 500'){
		Message({ message: errMsg, duration: 3 * 1000 })
	}else if(error.message === 'Request failed with status code 504'){
	   	Message({ message: errMsg + '   100504' , duration: 3 * 1000 })  
	}else if(error.message === 'timeout of 5000ms exceeded'){
	   	Message({ message: errMsg + '   100100' , duration: 3 * 1000 });
	}else if(error.message === 'Request failed with status code 401'){
        sessionStorage.removeItem('access-token');
        // localStorage.clear(); 
        Message({ message: timeMsg, duration: 3 * 1000 }); 
        setTimeout(function(){
            // alert('fetch');
            window.location.href = window.location.origin + "/login";
        }, 2000);
        // location.reload();
        // this.$router.push({ name: '登录', }).then(() => {
        // 	 location.reload(); // 为了重新实例化vue-router对象 避免bug
        // });
		}
    return Promise.reject(error);
  }
);

export default service;
